package com.cn.aam.checaiduo.ui.product;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableStringBuilder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.baoyz.widget.PullRefreshLayout;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bumptech.glide.Glide;
import com.cn.aam.checaiduo.Const;
import com.cn.aam.checaiduo.R;
import com.cn.aam.checaiduo.backend.RetrofitHome;
import com.cn.aam.checaiduo.backend.observer.OnRequestV2Listener;
import com.cn.aam.checaiduo.backend.rx.RxSchedulers;
import com.cn.aam.checaiduo.base.BaseActivity;
import com.cn.aam.checaiduo.base.ToolBarManager;
import com.cn.aam.checaiduo.bean.InfoOfDetailB;
import com.cn.aam.checaiduo.bean.ProductDetailB;
import com.cn.aam.checaiduo.bean.base.NormalResponseB;
import com.cn.aam.checaiduo.center.UserCenter;
import com.cn.aam.checaiduo.ui.arouter.UIRouter;
import com.cn.aam.checaiduo.ui.arouter.section.RouterMore;
import com.cn.aam.checaiduo.ui.homepage.pay.BuyProductConfirmActivity;
import com.cn.aam.checaiduo.ui.product.adapter.ImageOfProductDataAdapter;
import com.cn.aam.checaiduo.ui.product.adapter.InfoOfDetailAdapter;
import com.cn.aam.checaiduo.utils.MyTextViewUtils;
import com.cn.aam.checaiduo.utils.MyViewsUtils;
import com.cn.aam.checaiduo.utils.SpannableUtils;
import com.cn.aam.checaiduo.utils.TimeUtils;
import com.cn.aam.checaiduo.utils.WindowsUtils;
import com.cn.aam.checaiduo.widget.WMToast;
import com.flyco.tablayout.SegmentTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.orhanobut.logger.Logger;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author 微木森林
 * @time 2017/6/1 上午11:30
 * @description 项目详情页
 * @remark
 */
public class ProductDetailActivity extends BaseActivity {

    @BindView(R.id.banner_car)
    ConvenientBanner bannerCar;
    @BindView(R.id.recy_detail_item)
    RecyclerView recyDetailInfo;//基本信息
    @BindView(R.id.tab_layout_info)
    SegmentTabLayout tabLayoutInfo;//tab信息


    @BindView(R.id.tv_invest_amount)
    TextView tvInvestAmount;//投资信息
    @BindView(R.id.tv_title)
    TextView tvTitle;//标题

    @BindView(R.id.tv_raise_amount)
    TextView tvRaiseAmount;//众筹金额
    @BindView(R.id.tv_pre_amount)
    TextView tvPreAmount;//起投金额
    @BindView(R.id.tv_can_invest_money)
    TextView tvCanInvestMoney;//可投金额
    @BindView(R.id.tv_status)
    TextView tvStatus;//状态

    @BindView(R.id.tv_progress)
    TextView tvProgress;//字体进度
    @BindView(R.id.progressbar)
    ProgressBar progressbar;//进度条


    @BindView(R.id.tv_tab_tip)
    TextView tvTabTip;//项目资料提示，必须投资后才能浏览此内容
    @BindView(R.id.tv_tab_info)
    TextView tvTabInfo;//详情信息
    @BindView(R.id.recy_tab_info)
    RecyclerView recyTabInfo;//基本信息


    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.id_swipe)
    PullRefreshLayout idSwipe;

    private CountDownTimer cd;//倒计时

    private int currentCoverPostion = -1;
    private ProductDetailB detailData;


    private InfoOfDetailAdapter basicInfoAdapter;
    private ImageOfProductDataAdapter imageInfoAdapter;


    private String productID = "-1";
    private String sequence;

    private final static String DATA_PRODUCT_ID = "data_product_id";
    private final static String DATA_PRODUCT_SEQUENCE = "data_product_name";

    public static Intent newInstance(Context context, String productID, String sequence) {
        Intent intent = new Intent(context, ProductDetailActivity.class);
        intent.putExtra(DATA_PRODUCT_ID, productID);
        intent.putExtra(DATA_PRODUCT_SEQUENCE, sequence);
        return intent;
    }

    @Override
    protected int layoutId() {
        return R.layout.activity_product_detail;
    }

    @Override
    protected void onGenerate() {
        productID = getIntent().getStringExtra(DATA_PRODUCT_ID);
        sequence = getIntent().getStringExtra(DATA_PRODUCT_SEQUENCE);
        getProductDetailData();
    }


    private void getProductDetailData() {
        beginRefreshAnimation();
        RetrofitHome.getInstance()
                .getInternalApi()
                .getProductDetail(productID)
                .compose(RxSchedulers.<NormalResponseB<ProductDetailB>>toMain())
                .subscribe(new OnRequestV2Listener<ProductDetailB>(this) {
                    @Override
                    protected boolean isShowProgressBar() {
                        return false;
                    }

                    @Override
                    public void onNext(NormalResponseB<ProductDetailB> value) {
                        super.onNext(value);
                        if (value.getCode() == Const.REQUEST_SUCCESS) {
                            detailData = value.getData();
                            renderDetailPage(value.getData());
                        }
                        endRefreshAnimation();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        endRefreshAnimation();
                    }
                });
    }

    @Override
    protected void initView() {
        initToolbar();
        initRefreshLayout();
        initBanner();
        initBasicInfo();
        initTabInfo();
    }


    private void initRefreshLayout() {
        idSwipe.setOnRefreshListener(new PullRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getProductDetailData();
            }
        });
        //下拉刷新控件的配色
        idSwipe.setRefreshStyle(PullRefreshLayout.STYLE_MATERIAL);
        idSwipe.setColorSchemeColors(ContextCompat.getColor(mContext, R.color.colorPrimary));
    }

    private void initTabInfo() {
        //tab info
        //tabLayout
        String[] titles = {"车况描述", "项目资料", "风险需知"};
        tabLayoutInfo.setTabData(titles);
        tabLayoutInfo.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                switch (position) {
                    case 0:
                        showTab01();
                        break;
                    case 1:
                        showTab02(true);
                        break;
                    case 2:
                        showTab03();
                        break;
                }
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        //recy
        imageInfoAdapter = new ImageOfProductDataAdapter(mContext);
        recyTabInfo.setLayoutManager(new GridLayoutManager(mContext, 1));
        recyTabInfo.setItemAnimator(new DefaultItemAnimator());
        recyTabInfo.setAdapter(imageInfoAdapter);


        MyViewsUtils.hideAllViews(tvTabTip, tvTabInfo, recyTabInfo);
    }

    private void initBasicInfo() {
        //basic info
        basicInfoAdapter = new InfoOfDetailAdapter(mContext);
        recyDetailInfo.setLayoutManager(new GridLayoutManager(mContext, 1));
        recyDetailInfo.setItemAnimator(new DefaultItemAnimator());
        recyDetailInfo.setAdapter(basicInfoAdapter);
    }

    private void initBanner() {
        //banner
        MyViewsUtils.hideAllViews(bannerCar);
        //计算比例   600 / 800
        int bannerWidth = WindowsUtils.getScreenWidth(mContext);
        int bannerHeight = bannerWidth * 600 / 800;
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, bannerHeight);
        bannerCar.setLayoutParams(params);
    }

    private void initToolbar() {
        //toolbar
        ToolBarManager.with(this, WMContent)
                .setTitle("第" + sequence + "期")
                .setBackgroundColor(R.color.colorPrimary)
                .setNavigationIcon(R.drawable.ic_nav_arrow_white)
                .setRightMenuIconRes(R.drawable.ic_nav_share)
                .setRightMenuIconClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String url = detailData.getDetail_url();
                        String title = "第" + sequence + "期 " + detailData.getTitle();
                        String description = detailData.getDetail();
                        shareProduct(url, title, description);
                    }
                });
    }

    private void shareProduct(String shareUrl, String title, String description) {
        UMImage image = new UMImage(this, R.mipmap.ic_launcher);
        UMWeb web = new UMWeb(shareUrl);
        web.setTitle(title);//标题
        web.setThumb(image);  //缩略图
        web.setDescription(description);//描述

//        CustomDialogCenter.getInstance().showShareDialog(this, web);
        new ShareAction(this).setPlatform(SHARE_MEDIA.WEIXIN)
                .withMedia(web)
                .setCallback(umShareListener)
                .share();
    }


    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {
            //分享开始的回调
        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            WMToast.normal("邀请成功");
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            if (t.toString().contains("没有安装应用"))
                WMToast.normal("未安装微信应用");
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Logger.d("取消邀请");
        }
    };


    /**
     * @param data
     * @description 渲染详情页界面
     */
    private void renderDetailPage(ProductDetailB data) {
        //banner
        List<String> images = new ArrayList<>();

        List<ProductDetailB.ImageB> imageData = data.getImages();

        for (int i = 0; i < imageData.size(); i++) {
            images.add(imageData.get(i).getUrl());
        }

        if (images != null && images.size() > 0)
            showBanner(images);


        //status
        //annual yield & expired day
        SpannableStringBuilder builder1 = null;
        SpannableStringBuilder builder2 = null;
        SpannableStringBuilder builder3 = null;

        float annualYield = data.getExpect_yield_rate();
        String expiredDay = data.getExpired_day();

        switch (data.getStatus_code()) {
            case "1"://募集中
                tvStatus.setText("募集中");
                builder1 = SpannableUtils.colorByKeyWordWithReturn("预期年化收益 ≥" + annualYield + "% ", "≥" + annualYield + "%", R.color.colorPrimary);
                builder2 = SpannableUtils.colorByKeyWordWithReturn("回款天数 ≤" + expiredDay + "天 ", "≤" + expiredDay + "天", R.color.colorPrimary);
                tvInvestAmount.setText(builder1.append("，").append(builder2));
                break;
            case "21"://起息中
                tvStatus.setText("起息中");
                builder1 = SpannableUtils.colorByKeyWordWithReturn("预期年化收益 ≥" + annualYield + "% ", "≥" + annualYield + "%", R.color.colorPrimary);
                builder2 = SpannableUtils.colorByKeyWordWithReturn("回款天数 ≤" + expiredDay + "天 ", "≤" + expiredDay + "天", R.color.colorPrimary);
                tvInvestAmount.setText(builder1.append("，").append(builder2));
                break;
            case "41"://已回款
                tvStatus.setText("已回款");
                builder1 = SpannableUtils.colorByKeyWordWithReturn("单利年化 " + data.getSi_year_rate() + "% ", data.getSi_year_rate() + "%", R.color.colorPrimary);
                builder2 = SpannableUtils.colorByKeyWordWithReturn("复利年化 " + data.getYield_rate() + "% ", data.getYield_rate() + "%", R.color.colorPrimary);
                builder3 = SpannableUtils.colorByKeyWordWithReturn("回款天数 " + data.getDiff_day() + "天 ", data.getDiff_day() + "天", R.color.colorPrimary);
                tvInvestAmount.setText(builder1.append("，").append(builder2).append("，").append(builder3));
                break;
        }

        //title
        tvTitle.setText(data.getTitle());
        //basic info
        tvRaiseAmount.setText("" + data.getRaise_amount() + "元");
        tvPreAmount.setText("" + data.getPre_amount() + "元");
        tvCanInvestMoney.setText("" + data.getLeft_amount() + "元");


        //progress
        int progress = Integer.parseInt(data.getProgress()) > 100 ? 100 : Integer.parseInt(data.getProgress());
        tvProgress.setText("募集进度：" + progress + "%");

        ValueAnimator valueAnimator = ValueAnimator.ofInt(0, progress);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int progress = (int) animation.getAnimatedValue();
                if (progressbar != null)
                    progressbar.setProgress(progress);
            }
        });
        valueAnimator.setDuration(2000);
        valueAnimator.start();


        //basic info
        List<InfoOfDetailB> infoList = new ArrayList<>();
        infoList.add(new InfoOfDetailB("所在城市", data.getCity()));
        infoList.add(new InfoOfDetailB("上牌时间", data.getShangpai_date()));
        infoList.add(new InfoOfDetailB("行驶里程", data.getLicheng() + "公里"));
        infoList.add(new InfoOfDetailB("变速箱", data.getGearbox()));
        infoList.add(new InfoOfDetailB("排量", data.getPailiang()));
        basicInfoAdapter.setDataToAdapter(infoList);
        //tab info
        showTab01();

        //images
//        List<String> list = new ArrayList<>();
//        list.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1496663305479&di=703a4c0c81f258507fe7eeb791f71e70&imgtype=0&src=http%3A%2F%2Fwww.blccar.com%2Fuploads%2F2014-11-14%2F3229456e54ef0aeb94226296aa79c3f4.jpg");
//        list.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1496663305479&di=703a4c0c81f258507fe7eeb791f71e70&imgtype=0&src=http%3A%2F%2Fwww.blccar.com%2Fuploads%2F2014-11-14%2F3229456e54ef0aeb94226296aa79c3f4.jpg");
        imageInfoAdapter.setDataToAdapter(data.getProject().getMerchant_images());

        //btn
        switch (data.getStatus_code()) {
            case "1"://募集中
                String startTime = data.getStart_time();
                Date currentDate = Calendar.getInstance().getTime();//当前时间
                Date startDate = TimeUtils.String2Date(startTime, TimeUtils.DATE_FORMAT_TYPE_01);//开投时间
                if (currentDate.compareTo(startDate) < 0) {
                    startCountTime(startDate.getTime()-currentDate.getTime());
                    String timeStr = TimeUtils.Date2String(startDate, TimeUtils.DATE_FORMAT_TYPE_02);
                    btnSubmit.setText("开投时间：" + timeStr);
                    btnSubmit.setEnabled(false);
//                    btnSubmit.setBackgroundColor(Color.rgb(198, 198, 198));
                }
                break;
            case "21"://起息中
            case "41"://已回款
                tvCanInvestMoney.setText("已投满");
                btnSubmit.setText("已投满");
                btnSubmit.setEnabled(false);
                btnSubmit.setBackgroundColor(Color.rgb(198, 198, 198));
                break;
        }

    }


    /**
     * @description显示轮播
     */
    private void showBanner(final List<String> dataList) {
        MyViewsUtils.showAllViews(bannerCar);
        bannerCar.setPages(new CBViewHolderCreator<CardBannerHolderView>() {
            @Override
            public CardBannerHolderView createHolder() {
                return new CardBannerHolderView();
            }
        }, dataList);
        bannerCar.setPageIndicator(new int[]{R.drawable.ic_indicator, R.drawable.ic_indicator_focus});
        bannerCar.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currentCoverPostion = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        bannerCar.setCanLoop(false);
        if (currentCoverPostion != -1)
            bannerCar.setcurrentitem(currentCoverPostion);
    }


    /**
     * @description 轮播所需  协助类
     */
    class CardBannerHolderView implements Holder<String> {
        ImageView imageView;

        @Override
        public View createView(Context context) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View view = inflater.inflate(R.layout.banner_item_product_detail, null);
            imageView = (ImageView) view.findViewById(R.id.imageView);
            return view;
        }

        @Override
        public void UpdateUI(Context context, int position, String data) {
            Glide.with(mContext).load(data).asBitmap().centerCrop().placeholder(R.color.black_alpha20).into(imageView);
        }
    }


    @OnClick(R.id.btn_submit)
    public void onClickToBuy() {
        //判断是否登录
        if (needLogin())
            return;
        //判断是否实名认证
        if (UserCenter.getInstance().getUser().getAuth_status().equals("0")) {
            WMToast.normal("请先进行实名认证");
            UIRouter.getInstance().openPage(mContext, UIRouter.MORE.AUTH);
            return;
        }
        //判断是否双击
        if (!MyViewsUtils.isFastDoubleClick()) {
            startActivity(BuyProductConfirmActivity.newInstance(mContext, detailData));
        }

    }


    /**
     * @description tab01 车辆描述
     */
    private void showTab01() {
        tvTabInfo.setText(MyTextViewUtils.toDBC(detailData.getDetail()));

        MyViewsUtils.hideAllViews(tvTabTip, tvTabInfo, recyTabInfo);
        MyViewsUtils.showAllViews(tvTabInfo);
    }


    /**
     * @description tab02 项目资料
     */
    private void showTab02(boolean isInvested) {
        tvTabInfo.setText(detailData.getProject().getMerchant_information());

        MyViewsUtils.hideAllViews(tvTabTip, tvTabInfo, recyTabInfo);
        if (isInvested)
            MyViewsUtils.showAllViews(tvTabInfo, recyTabInfo);
        else
            MyViewsUtils.showAllViews(tvTabTip);
    }

    /**
     * @description tab03 风险须知
     */
    private void showTab03() {
        tvTabInfo.setText(detailData.getRisk_notes());

        MyViewsUtils.hideAllViews(tvTabTip, tvTabInfo, recyTabInfo);
        MyViewsUtils.showAllViews(tvTabInfo);
    }


    private void beginRefreshAnimation() {
        idSwipe.post(new Runnable() {
            @Override
            public void run() {
                idSwipe.setRefreshing(true);
            }
        });
    }

    private void endRefreshAnimation() {
        idSwipe.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (idSwipe != null)
                    idSwipe.setRefreshing(false);

            }
        }, 1000);
    }


    /**
     * 开始倒计时
     */
    private void startCountTime(long countDown) {
        //倒计时60s
        if (cd!=null) return;
        cd = new CountDownTimer(countDown, 1000) {
            @Override
            public void onTick(long l) {
                //Logger.e("开投倒计时\n" + TimeUtils.formatSecondTime(l / 1000));
                //btnSubmit.setText("开投倒计时\n" + TimeUtils.formatSecondTime(l / 1000));
            }

            @Override
            public void onFinish() {
                endCountTime();
                btnSubmit.setEnabled(true);
                btnSubmit.setText("立即购买");
            }
        };
        cd.start();
    }

    /**
     * 结束倒计时
     */
    private void endCountTime() {
        if (cd != null) {
            cd.cancel();
            cd = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        endCountTime();
    }
}
